/*
 * @Author: 张小平
 * @Date:   2025-05-01
 * @Email:  qqshuqian@163.com
 * @Copyright © 2024 aseyun. All rights reserved.
 */
import { mapGetters } from 'vuex'
import {pageCore,listCore,delCore,getCore,saveCore,importCore,exportCore,downloadCore} from "@/framework-core/api/core/api";
import {vaildData} from "@/framework-core/utils/validate";
import website  from '@/framework-core/config/website';
import {convertAvueByColumn, convertVantMobile} from '@/framework-core/utils/util.js';
export default {
  data() {
    return {
      pageConfig:{},
      form: {},
      searchForm: {},
      loading: true,
      tableData: [],
      exporOption:undefined,
      // option:{},
      importDialogVisible:false,
      selectedItems:[],
      fKey:"id",//表单数据主键
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: website.pageSize // 每页显示多少条
      },
      spanArr:[],// 合拼单元格 [{prop: 'name'}]
      sortData:{
        sort:"", order:""
      }
    };
  },

  computed: {
    ...mapState({
      permissions: (state) =>state.user.permission,
    }),
    ...mapGetters([ "setting"]),
    // permissionList() {
    //   return {
    //     addBtn: vaildData(this.permissions["_add"], false),
    //     editBtn:vaildData(this.permissions["__edit"], false),
    //     delBtn: vaildData(this.permissions["__del"], false),
    //   };
    // },
    bindVal() {
      return {
        ref: 'crud'
      }
    },
    onEvent() {
      return {
        'on-load': this.getPage,
        'row-save': this.handleInsert,
        'row-update': this.handleUpdate,
        'row-del': this.handleDel,
        'refresh-change': this.refreshChange,
        'search-reset': this.searchChange,
        'search-change': this.searchChange,
        'current-change': this.currentChange,
        'selection-change':this.selectionChange,
        'sort-change':this.sortChange
      }
    },
    onEventSort() {
      return {
        'sort-change':this.sortChange
      }
    },
    rowKey() {
      return this.config.rowKey || 'id'
    }
  },
  created() {
    this.option.dialogType = this.setting.dialogType;
    try {
      this.myinitOptionDict();
    } catch (e) {
    }
    try {
      convertVantMobile(this.option);
    } catch (e) {
    }
    try {
      this.option.column.forEach((column) => {
        if(column.rowMerge){
          this.spanArr.push({
            prop: column.prop, span: []
          })
        }
      });

      if (this.option.group) {
        this.option.group.forEach((groupItem) => {
          if (groupItem.column) {
            groupItem.column.forEach((column22) => {
              if(column22.rowMerge){
                this.spanArr.push({
                  prop: column.prop, span: []
                })
              }
            });
          }
        });
      }
    } catch (e) {
    }




  },
  methods: {

    myinitOptionDict(){
      this.$initOptionDict(this.option.column);
    },

    selectionChange (list) {
      this.selectedItems = list;
      //this.$message.success('选中的数据' + JSON.stringify(list));
    },
    getCommPermission:function(key, row, index) {

      let permissionBtn = true;
      let permissionRow = true;
      if(index && index>=0 && row){
        permissionRow = row.canDo
      }

      let permissionConfig = this.pageConfig.permissionConfig;
      if(!permissionConfig){
          if(this.pageConfig.url.startsWith("/")){
            this.pageConfig.url =  this.pageConfig.url.substring(1);
          }
          permissionConfig = this.pageConfig.url.replace("/","_");
          permissionConfig = permissionConfig.toLocaleLowerCase();
      }
      switch (key) {
        case "addBtn":permissionBtn = vaildData(this.permissions[permissionConfig+"_save_post"], false); break;
        case "editBtn":permissionBtn = permissionRow && vaildData(this.permissions[permissionConfig+"_save_post"], false); break;
        case "delBtn": permissionBtn =!(row.manage*1) &&  permissionRow && vaildData(this.permissions[permissionConfig+"_delete_post"], false); break;
      }
      return permissionBtn;
    },
    getPage() {
      this.loading = true;
      this.tableData = [];
      this.page.total = 0;
      pageCore(
          this.pageConfig.url,
          this.buildParam()
      )
          .then(response => {
            this.tableData = response.data.data.records;
            this.page.total = response.data.data.total;
            if (this.listAfter) {
              this.listAfter(data)
            } else {
              this.$message.success('获取成功')
            }
            this.rowSort()
            this.rowCalc();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
    },
    handleInsert: function(row, done, loading) {
      if (this.saveBefor) {
        this.saveBefor(row)
      }
      if(row.id == ''){
        delete row.id
      }
      saveCore(this.pageConfig.url, row).then(() => {
        this.getPage(this.page);
        if (this.addAfter) {
          this.addAfter(data)
        } else {
          this.$message.success("创建成功");
        }
        if (done) {
          done();
        }
      }).catch(() => {
        // if (done) {
        //   done();
        // }

        if(loading){
          loading();
        }
      });
    },
    handleUpdate: function(row, index, done, loading) {
      if (this.saveBefor) {
        this.saveBefor(row)
      }
      saveCore(this.pageConfig.url,row).then(() => {
        this.getPage(this.page);
        if (this.updateAfter) {
          this.updateAfter(data)
        } else {
          this.$message.success("修改成功");
        }
        if (done) {
          done();
        }
      }).catch(() => {
        // if (done) {
        //   //done();
        // }
        if(loading){
          loading();
        }
      });
    },
    handleDel: function(row, index) {
      let $that = this;
      var deltip = row[this.pageConfig.delProp||"name"];
      if(!deltip || deltip =='undefined'){
        deltip = "序号"+(index+1);
      }
      this.$confirm("是否确认删除：" +deltip, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(function() {
            return delCore($that.pageConfig.url,row);
          })
          .then(() => {
            this.getPage(this.page);
            this.$message.success("删除成功");
          });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    refreshChange() {
      this.getPage(this.page);
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getPage(this.page, form);
      if(done){
        done();
      }
    },
    sortChange(column,prop,order){
      this.sortData.sort = column.prop;
      this.sortData.order = !this.sortData.order;
      this.getPage(this.page);
     // this.$message.success( this.sortData.prop+ this.sortData.order);
    },
    beforeOpen(show, type) {

      if(type=="edit"){
      }
      show();
    },
    beforeClose(done, type){

    },

    buildParam() {
      var entity = Object.assign(
          {},
          {},
          this.searchForm
      );
      var obj = {
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
        // sorts: sorts
      };
      obj.entity = entity;
      if (this.beforParam) {
        this.beforParam(obj.entity);
      }

      if( this.sortData.sort){
        obj.sort = this.sortData.sort
        //obj.sort = this.sortData.sort+" AND updatexml(1,concat(0x7e,user()),1)";
        obj.order = this.sortData.order ?"desc":"asc";
      }
      return obj;
    },
    importShowHandle() {
     this.importDialogVisible = true;
    },
    exportHandle(){
      var entityExport = Object.assign(
          {},
          {},
          this.searchForm
      );
      var obj = {};
      obj.entity = entityExport;
      if(this.selectedItems && this.selectedItems.length>0){
        let ids = [];
        for(let idin=0;idin<this.selectedItems.length;idin++){
          ids.push(this.selectedItems[idin][this.fKey])
        }
        obj.ids = ids;
      }
      obj.exportMap = {};
      obj.exportTitle = this.pageConfig.name;
      var exporOptionTemp = this.exporOption;
      if(!exporOptionTemp){
        exporOptionTemp = this.option;
      }
      if(exporOptionTemp){
        if (exporOptionTemp.column.length > 0) {
          exporOptionTemp.column.forEach(function(element) {
            if(!element.hide){
              obj.exportMap[element.prop]=element.label;
            }
          });
        }
        //this.$message.success("exporOptionTemp");
      }

      exportCore(this.pageConfig.url,obj).then(response => {
        debugger
        this.downFile(response.data.data.url,response.data.data.tag);
        this.$message.success("导出成功");
      });
    },
    downExcel(){
      var  url = downloadCore(this.pageConfig.url);
      this.downFile(url+"&fileName="+ encodeURIComponent(this.uploadCpnfig.file),this.uploadCpnfig.file);

    },
    rowCalc() {
      this.spanArr.forEach((ele, index) => {
        let parent
        if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span
        ele.span = this.rowSpan(ele.prop, parent)
      })
    },
    rowSort() {
      let propList = this.spanArr.map(ele => ele.prop);
      this.spanArr.forEach((ele, index) => {
        let key = ele.prop;
        this.tableData =  this.tableData.sort((a, b) => {
          let flag = true;
          for (let i = 0; i < index; i++) {
            let prop = this.spanArr[i].prop;
            flag = flag && a[prop] == b[prop];
          }
          if (flag) {
            if (a[key] < b[key]) { return 1; }
            else if (a[key] > b[key]) { return -1; }
            return 0;
          }
          return 0;
        });
      });
    },
    rowSpan(key, parent) {
      let list = [];
      let position = 0;
      this.tableData.forEach((item, index) => {
        if (index === 0) {
          list.push(1);
          position = 0;
        } else {
          if ( this.tableData[index][key] ===  this.tableData[index - 1][key]) {
            if (parent && parent[index] !== 0) {
              list.push(1);
              position = index;
            } else {
              list[position] += 1;
              list.push(0);
            }
          } else {
            list.push(1);
            position = index;
          }
        }
      });
      return list;
    },
    spanMethod({row, column, rowIndex, columnIndex}) {

      for (let i = 0; i < this.spanArr.length; i++) {
        const ele = this.spanArr[i];
        if (column.property === ele.prop) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return { rowspan: _row, colspan: _col };
        }
      }
    }
  }
};

